#!/usr/bin/python
#
# Copyright (c) 2009 Julius Volz
# See LICENSE for details.

import config, csv, datetime, debug, rdflib

def output(links, link_type, namespace, file, format):
  output_fn = formats.get(format, output_n3)
  return output_fn(links, link_type, namespace, file)

def output_n3(links, link_type, namespace, file):
  for link in links:
    link_str = '<%s> <%s> <%s> .\n' % (link['src'], link_type, link['dst'])
    debug.log(7, link_str)
    file.write(link_str)

def output_n3_debug(links, link_type, namespace, file):
  for link in links:
    link_str = '[%s]: <%s> <%s> <%s> .\n' % (link['similarity'], link['src'],
                                           link_type, link['dst'])
    debug.log(7, link_str)
    file.write(link_str)

def output_n3_reified(links, link_type, namespace, file):
  date = datetime.date.today()

  g = rdflib.ConjunctiveGraph()
  g.bind('silk', 'http://www4.wiwiss.fu-berlin.de/silk/')
  g.bind('interlink', namespace)
  silk_pfx = rdflib.Namespace('http://www4.wiwiss.fu-berlin.de/silk/')
  link_pfx = rdflib.Namespace(namespace)
  rdfs_pfx = rdflib.Namespace('http://www.w3.org/2000/01/rdf-schema#')
  rdf_pfx = rdflib.Namespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#')

  i = 1
  for link in links:
    link_uri = link_pfx['link_%s' % i]

    g.add((link_uri, rdfs_pfx['label'], rdflib.Literal('Link %s' % i)))
    g.add((link_uri, rdf_pfx['type'], silk_pfx['interlink']))
    g.add((link_uri, silk_pfx['confidence'], rdflib.Literal(link['similarity'])))
    g.add((link_uri, silk_pfx['date'], rdflib.Literal(date)))
    g.add((link_uri, silk_pfx['link_source'], rdflib.URIRef(link['src'])))
    g.add((link_uri, silk_pfx['link_target'], rdflib.URIRef(link['dst'])))
    g.add((link_uri, silk_pfx['link_type'], rdflib.URIRef(link_type)))
    i += 1

  file.write(g.serialize(format='n3'))

def output_csv(links, link_type, namespace, file):
  writer = csv.writer(file, delimiter=';', dialect='excel', quotechar='|',
                      quoting=csv.QUOTE_MINIMAL)
  writer.writerow(['Similarity', 'Source', 'Link', 'Target'])
  for link in links:
    writer.writerow([link['similarity'], link['src'], link_type, link['dst']])

formats = {
  'n3': output_n3,
  'n3_debug': output_n3_debug,
  'n3_reified': output_n3_reified,
  'csv': output_csv
}
